package com.ltu.payment;


import java.io.File;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;

import com.ltu.domain.mp_entity.PayRecord;
import com.ltu.domain.mp_entity.customize.CompanyEntity;
import com.ltu.domain.mp_entity.customize.RefunRecordEntity;
import com.ltu.enums.EnumUtils;
import com.ltu.payment.config.WxAppPayConfig;
import com.ltu.payment.enums.PayWayDict;
import com.ltu.payment.util.XmlUtils;
import com.ltu.util.common.StrUtils;
import com.ltu.util.exception.ApiException;
import com.ltu.util.http.HttpPostUtil;

import lombok.extern.slf4j.Slf4j;


/**
 * @Description:微信下单 退款
 * @author: 若尘
 * @date 2019年10月14日 下午4:18:50
 * @version V1.0
 */
@Slf4j
@Component
public class PubPayService {  
	
	@Autowired
	private MyWxPayServices wxPayService;
	@Autowired
	private WxPayServices2 wxPayServices2;

//	@Value("${wx.miniapp.appid}")
//	private String appId;
//	@Value("${wx.pay.mchId}")
//	private String mchId;
//	@Value("${wx.pay.mchKey}")
//	private String mchKey;

	/**
	 * 功能：统一下单拉起收银接口
	 * 
	 * @param payRecordReq
	 * 
	 */
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public JSONObject placeOrder(PayRecord payRecord, String openId,String ip) {
		
		JSONObject map = new JSONObject();
		
		if (payRecord == null)
			throw new ApiException(50000, "PayRecord ");
		
		PayWayDict payWay=	 EnumUtils.indexToEnum(PayWayDict.class, payRecord.getPayWay());
		
		if ( PayWayDict.WxPayway.equals(payWay) ){//微信支付
			// 服务商模式
				map = wxPayServices2.placeOrder(payRecord, openId, ip);
			
		} else if (PayWayDict.WxAppPayway.equals(payWay)) { // 微信APP支付
			
			map = wxPayService.placeOrderByApp(payRecord, ip);
		}
		else {
			throw new ApiException(50000, "payWay参数错误错误");
		}
		System.out.print("-------签名信息: " + map);
		if (map.isEmpty()) {
			map.put("code", "40004");
			map.put("message", "拉起收银台失败");
			return map;
		}
		return map;
	}
	
	/**
	 * 
	 * @date 2019年2月25日
	 * @author 若尘
	 * @Description 申请微信官方退款
	 * @param mchId
	 * @param payKey =  @see WxAppPayConfig.WxMchKey
	 * @param certFileName 证书文件名称
	 * @param refunRecord
	 *            void
	 */
	public Boolean sendRefund(RefunRecordEntity refunRecord,CompanyEntity  c) {
		Boolean  flag = false;
		String url =   WxAppPayConfig.REFUND;
		refunRecord.setRefundAppid(c.getAppId());
		Map<String, Object> param = new HashMap<>();
		param.put("appid", refunRecord.getRefundAppid());
		// 商户编号
		param.put("mch_id", c.getMchId());
		param.put("nonce_str", StrUtils.getRandmStr(4));
		// 我们的订单号
		param.put("transaction_id", refunRecord.getPayCode());// "mfb2018122818051143"
		param.put("out_refund_no", refunRecord.getOutRefundNo());
		param.put("total_fee", refunRecord.getTotalMoney());
		param.put("refund_fee", refunRecord.getRefundMoney());
		String xmlStr = XmlUtils.paramSort(param,c.getMchKeyApi2());
		System.out.println("\n 请求的xml参数为：" + xmlStr);
		String result = "";
		Map<String, String> resultMap = null;

		String userDir = System.getProperties().getProperty("user.dir").concat(File.separator).concat("cert");
		String path = userDir.concat(File.separator).concat(c.getMchId() +".p12");
//		String userDir =  this.getClass().getClassLoader().getResource("").getPath();
// 		String path = userDir.concat("apiclient_cert.p12");
		try {
			result = HttpPostUtil.sendPost_PKCS12(url, xmlStr, c.getMchId(), path);
			System.out.println("返回结果：" + result);
			log.info("本次申请退款结果：" + result);
			resultMap = XmlUtils.toMap(result.getBytes(), "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 退款状态0=退款失败1=退款成功2=退款中3=等待审核4=通过审核或者无需审核5=申请退款异常
		StringBuilder subStr = new StringBuilder("");
		if (!resultMap.get("return_code").equals("SUCCESS")) {
			refunRecord.setStatus(5);
			subStr.append("\n 申请微信退款失败,退款单号为：");
			subStr.append(refunRecord.getId());
			subStr.append(" \n 请求状态：");
			subStr.append(resultMap.get("return_code"));
			subStr.append("\t ,错误描述：");
			subStr.append(resultMap.get("return_msg"));
			refunRecord.setRefundRemark(subStr.toString());
			refunRecord.setStatusDescription(subStr.toString());
			refunRecord.setRefundId(resultMap.get("refund_id"));
		} else {
			if (resultMap.get("result_code").equals("SUCCESS")) {
				refunRecord.setStatus(2);
				refunRecord.setRefundRemark("申请退款成功,退款处理中");
				refunRecord.setStatusDescription("申请退款成功,退款处理中");
				refunRecord.setRefundId(resultMap.get("refund_id"));
				flag = true;
			}else{
				refunRecord.setStatus(5);
				subStr.append("\n 退款失败,退款状态码为：");
				subStr.append(resultMap.get("result_code"));
				subStr.append("\t ,错误号为：");
				subStr.append(resultMap.get("err_code"));
				subStr.append("\t ,错误描述：");
				subStr.append(resultMap.get("err_code_des"));
				refunRecord.setRefundRemark(subStr.toString());
				refunRecord.setStatusDescription(subStr.toString());
				refunRecord.setRefundId(resultMap.get("refund_id"));
			}

		}
		return flag;

	}
	
	

}
